import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:short_drama/pages/detail/detail_viewmodel.dart';
import 'package:short_drama/views/nav_bar.dart';

class DetailPage extends StatefulWidget {
  final String dramaId;

  const DetailPage(this.dramaId, {super.key});

  @override
  State<DetailPage> createState() => _DetailPageState();
}

class _DetailPageState extends State<DetailPage> with WidgetsBindingObserver {
  final DetailViewmodel viewModel = DetailViewmodel();

  @override
  void initState() {
    super.initState();
    viewModel.dramaId = widget.dramaId;
    viewModel.queryDetail();
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  void didChangeMetrics() {
    super.didChangeMetrics();
    final Size size = WidgetsBinding.instance.window.physicalSize;
    final double scale = WidgetsBinding.instance.window.devicePixelRatio;
    final double height = size.height / scale;
    final double bottomInset = WidgetsBinding.instance.window.viewInsets.bottom;
    setState(() {
      viewModel.isKeyBoardShow.value = bottomInset > 0;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: const Color(0xf00a0f12),
      child: Obx(
        () => Stack(
          children: [
            _infoView(),
            _buyBtn(),
            NavBarView(),
            if (viewModel.showBuy.value) _buyView(),
          ],
        ),
      ),
    );
  }

  Widget _infoView() {
    return SingleChildScrollView(
      child: Obx(
        () => Stack(
          children: [
            if (viewModel.detailModel.value != null)
              SizedBox(
                height: 295,
                width: double.infinity,
                child: Image.network(
                  viewModel.detailModel.value?.drama_image ?? '',
                  fit: BoxFit.cover,
                ),
              ),
            if (viewModel.detailModel.value != null)
              SizedBox(
                width: double.infinity,
                child: Column(
                  children: [
                    SizedBox(height: 227, width: double.infinity),
                    Container(
                      padding: EdgeInsets.all(16),
                      child: Row(
                        crossAxisAlignment: CrossAxisAlignment.end,
                        children: [
                          SizedBox(
                            height: 113,
                            width: 95,
                            child: Image.network(
                              viewModel.detailModel.value?.drama_image ?? '',
                              fit: BoxFit.cover,
                            ),
                          ),
                          Expanded(
                            child: Padding(
                              padding: EdgeInsets.only(left: 16),
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Text(
                                    viewModel.detailModel.value?.drama_name ??
                                        '',
                                    style: TextStyle(
                                      fontSize: 22,
                                      fontWeight: FontWeight.bold,
                                      color: Colors.white,
                                    ),
                                  ),
                                  Padding(
                                    padding: EdgeInsets.only(top: 8, bottom: 8),
                                    child: Row(
                                      children: [
                                        Text(
                                          '导演: ${viewModel.detailModel.value?.drama_desc}',
                                          style: TextStyle(
                                            fontSize: 13,
                                            color: Color(0xaaffffff),
                                          ),
                                        ),
                                        Spacer(),
                                        Text(
                                          '项目周期: ${viewModel.detailModel.value?.drama_period}天',
                                          style: TextStyle(
                                            fontSize: 13,
                                            color: Color(0xaaffffff),
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                                  Row(
                                    crossAxisAlignment:
                                        CrossAxisAlignment.center,
                                    children: [
                                      if ((viewModel
                                                  .detailModel
                                                  .value
                                                  ?.drama_status ??
                                              0) ==
                                          1)
                                        Text(
                                          '剩余库存：',
                                          style: TextStyle(
                                            fontSize: 13,
                                            color: Color(0xaaffffff),
                                          ),
                                        ),
                                      if ((viewModel
                                                  .detailModel
                                                  .value
                                                  ?.drama_status ??
                                              0) ==
                                          1)
                                        Padding(
                                          padding: EdgeInsets.only(
                                            left: 4,
                                            right: 10,
                                            top: 3,
                                          ),
                                          child: ClipRRect(
                                            borderRadius: BorderRadius.circular(
                                              10,
                                            ),
                                            child: SizedBox(
                                              width: 103,
                                              height: 7,
                                              child: LinearProgressIndicator(
                                                value:
                                                    (viewModel
                                                            .detailModel
                                                            .value
                                                            ?.drama_period ??
                                                        0) /
                                                    100,
                                                backgroundColor: Colors.white,
                                                valueColor:
                                                    AlwaysStoppedAnimation(
                                                      Color(0xff0b9970),
                                                    ),
                                              ),
                                            ),
                                          ),
                                        ),
                                      if ((viewModel
                                                  .detailModel
                                                  .value
                                                  ?.drama_status ??
                                              0) ==
                                          2)
                                        Text(
                                          viewModel
                                                  .detailModel
                                                  .value
                                                  ?.end_time ??
                                              '',
                                          style: TextStyle(
                                            fontSize: 13,
                                            color: Color(0xaaffffff),
                                          ),
                                        ),
                                      if ((viewModel
                                                  .detailModel
                                                  .value
                                                  ?.drama_status ??
                                              0) ==
                                          3)
                                        Text(
                                          '活动发放中',
                                          style: TextStyle(
                                            fontSize: 13,
                                            color: Color(0xaaffffff),
                                          ),
                                        ),
                                      // if ((viewModel.detailModel.value?.stock ??
                                      //         0) >
                                      //     0)
                                      //   Text(
                                      //     '${viewModel.detailModel.value?.stock}',
                                      //     style: TextStyle(
                                      //       fontSize: 13,
                                      //       color: Color(0xaaffffff),
                                      //     ),
                                      //   ),
                                    ],
                                  ),
                                ],
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                    _tabItems(),
                    Obx(() => _tabContent()),
                  ],
                ),
              ),
          ],
        ),
      ),
    );
  }

  Widget _tabItems() {
    return SizedBox(
      height: 58,
      child: Obx(
        () => Row(
          children: [
            SizedBox(width: 16),
            ...viewModel.titles.map((title) {
              return Obx(
                () => GestureDetector(
                  onTap: () {
                    var index = viewModel.titles.indexOf(title);
                    viewModel.titleIndex.value = index;
                  },
                  child: Container(
                    height: 28,
                    padding: EdgeInsets.only(left: 18, right: 18),
                    margin: EdgeInsets.only(right: 8),
                    decoration: BoxDecoration(
                      color:
                          viewModel.titles[viewModel.titleIndex.value] == title
                              ? Color.fromARGB(32, 255, 255, 255)
                              : Colors.transparent,
                      borderRadius: BorderRadius.circular(14),
                    ),
                    child: Text(
                      title,
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 17,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                ),
              );
            }),
          ],
        ),
      ),
    );
  }

  Widget _tabContent() {
    if (viewModel.titleIndex.value == 0) {
      return _introView();
    }
    if (viewModel.titleIndex.value == 1) {
      return _actorsView();
    }
    return Container();
  }

  Widget _introView() {
    return Container(
      width: double.infinity,
      padding: EdgeInsets.all(22),
      margin: EdgeInsets.only(left: 16, right: 16),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(15),
        color: Color(0x0affffff),
      ),
      child: Text(
        viewModel.detailModel.value?.drama_content ?? '',
        style: TextStyle(color: Colors.white, fontSize: 12, height: 2.5),
      ),
    );
  }

  Widget _actorsView() {
    return Container(
      width: double.infinity,
      padding: EdgeInsets.all(22),
      margin: EdgeInsets.only(left: 16, right: 16),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(15),
        color: Color(0x0affffff),
      ),
      child: Wrap(
        spacing: _gridSpace(),
        runSpacing: _gridSpace(),
        children: [
          ...(viewModel.detailModel.value?.actor ?? []).map((a) {
            return SizedBox(
              width: 54,
              child: Column(
                children: [
                  Image.network(
                    a.headimg ?? '',
                    height: 54,
                    width: 54,
                    fit: BoxFit.cover,
                  ),
                  Padding(
                    padding: EdgeInsets.only(top: 8, bottom: 4),
                    child: Text(
                      a.real_name ?? '',
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(color: Colors.white, fontSize: 10),
                    ),
                  ),
                  Text(
                    a.nick_name ?? '',
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(color: Colors.white, fontSize: 10),
                  ),
                ],
              ),
            );
          }),
        ],
      ),
    );
  }

  Widget _buyBtn() {
    return Positioned(
      right: 14,
      bottom: 90,
      child: IconButton(
        onPressed: () {
          viewModel.changeShowBuy();
        },
        icon: Image.asset('assets/images/btn_buy.png', scale: 3),
      ),
    );
  }

  Widget _buyView() {
    return GestureDetector(
      onTap: () {
        if (viewModel.isKeyBoardShow.value) {
          FocusScope.of(context).unfocus();
        } else {
          viewModel.changeShowBuy();
        }
      },
      child: Container(
        color: Color(0x66000000),
        width: double.infinity,
        height: double.infinity,
        child: Stack(
          alignment: Alignment.bottomCenter,
          children: [
            Padding(
              padding: EdgeInsets.only(
                bottom: viewModel.isKeyBoardShow.value ? 200 : 0,
              ),
              child: GestureDetector(
                onTap: () {},
                child: Container(
                  height: 311,
                  decoration: BoxDecoration(
                    color: Color(0xff161b1e),
                    borderRadius: BorderRadius.only(
                      topLeft: Radius.circular(10),
                      topRight: Radius.circular(10),
                    ),
                  ),
                  child: Column(
                    children: [
                      Padding(
                        padding: EdgeInsets.only(top: 16, left: 16, right: 16),
                        child: Row(
                          children: [
                            SizedBox(
                              width: 95,
                              height: 113,
                              child: Image.network(
                                viewModel.detailModel.value?.drama_image ?? '',
                                fit: BoxFit.cover,
                              ),
                            ),
                            Container(
                              padding: EdgeInsets.only(left: 16),
                              height: 113,
                              child: Column(
                                children: [
                                  Text(
                                    viewModel.detailModel.value?.drama_name ??
                                        '',
                                    style: TextStyle(
                                      color: Colors.white,
                                      fontSize: 22,
                                    ),
                                  ),
                                  Spacer(),
                                  Row(
                                    children: [
                                      Image.asset(
                                        'assets/images/icon_home_list_coin.png',
                                        width: 13,
                                        height: 13,
                                      ),
                                      SizedBox(width: 4),
                                      Text(
                                        '${viewModel.detailModel.value?.point ?? ''}/份',
                                        style: TextStyle(
                                          color: Color(0xfffbb11b),
                                          fontSize: 15,
                                        ),
                                      ),
                                    ],
                                  ),
                                ],
                              ),
                            ),
                          ],
                        ),
                      ),
                      Container(
                        height: 50,
                        padding: EdgeInsets.only(left: 16, right: 16),
                        margin: EdgeInsets.only(bottom: 24),
                        child: Row(
                          children: [
                            Text(
                              '限购份额：${viewModel.detailModel.value?.max_num}',
                              style: TextStyle(
                                color: Colors.white54,
                                fontSize: 12,
                              ),
                            ),
                            Spacer(),
                            Row(
                              children: [
                                GestureDetector(
                                  onTap: () {
                                    if (viewModel.buyCount.value > 1) {
                                      viewModel.buyCount.value--;
                                      viewModel.editTextController.text =
                                          '${viewModel.buyCount.value}';
                                    }
                                  },
                                  child: Container(
                                    width: 20,
                                    height: 20,
                                    decoration: BoxDecoration(
                                      color: Color(0xffEAEDF2),
                                      borderRadius: BorderRadius.circular(4),
                                    ),
                                    child: Text(
                                      '-',
                                      textAlign: TextAlign.center,
                                      style: TextStyle(
                                        color: Color(0xffBABDC2),
                                      ),
                                    ),
                                  ),
                                ),
                                SizedBox(
                                  width: 34,
                                  height: double.infinity,
                                  child: TextField(
                                    controller: viewModel.editTextController,
                                    keyboardType: TextInputType.number,
                                    decoration: InputDecoration(
                                      border: InputBorder.none,
                                    ),
                                    textAlign: TextAlign.center,
                                    textAlignVertical: TextAlignVertical(
                                      y: -0.5,
                                    ),
                                    style: TextStyle(
                                      color: Colors.white,
                                      fontSize: 14,
                                    ),
                                    onChanged: (text) {
                                      if (text.isEmpty ||
                                          int.parse(text) == 0) {
                                        viewModel.editTextController.text = '1';
                                      }
                                      viewModel.buyCount.value = int.parse(
                                        text,
                                      );
                                    },
                                  ),
                                ),
                                GestureDetector(
                                  onTap: () {
                                    viewModel.buyCount.value++;
                                    viewModel.editTextController.text =
                                        '${viewModel.buyCount.value}';
                                  },
                                  child: Container(
                                    width: 20,
                                    height: 20,
                                    decoration: BoxDecoration(
                                      color: Color(0xff2D83EE),
                                      borderRadius: BorderRadius.circular(4),
                                    ),
                                    child: Text(
                                      '+',
                                      textAlign: TextAlign.center,
                                      style: TextStyle(color: Colors.white),
                                    ),
                                  ),
                                ),
                              ],
                            ),
                          ],
                        ),
                      ),
                      Container(
                        width: double.infinity,
                        height: 52,
                        margin: EdgeInsets.only(left: 36, right: 36),
                        child: TextButton(
                          style: TextButton.styleFrom(
                            backgroundColor: Color(0xff0B9970),
                            foregroundColor: Colors.white,
                          ),
                          onPressed: () {
                            viewModel.queryPurchase(
                              viewModel.dramaId,
                              '${viewModel.buyCount.value}',
                            );
                          },
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Image.asset(
                                'assets/images/icon_home_list_coin.png',
                                width: 13,
                                height: 13,
                              ),
                              SizedBox(width: 4),
                              Text(
                                '${int.parse(viewModel.detailModel.value?.point ?? '0') * viewModel.buyCount.value}',
                                style: TextStyle(
                                  color: Colors.white,
                                  fontSize: 15,
                                ),
                              ),
                            ],
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  double _gridSpace() {
    final int minWidth = 29;
    final int itemWidth = 54;
    final int oneWidth = minWidth + itemWidth;
    double maxWidth = MediaQuery.of(context).size.width - 76;
    int maxNum = maxWidth ~/ oneWidth;
    double outWidth = maxWidth - maxNum * oneWidth + minWidth;
    return outWidth / (maxNum - 1) + minWidth;
  }
}
